import sys
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi_offline import FastAPIOffline
from loguru import logger

from app.routes import api_router

format_ = (
    "<g>[{time:YYYY-MM-DD HH:mm:ss.SSS}</g>][<lvl>{level}</lvl>]"
    "[{thread.name}][{name}:{function}:{line}]"
    " - <lvl>{message}</lvl>"
)
logger.remove()
logger.add(
    sys.stderr,
    format=format_,
    backtrace=True,
    diagnose=True,
)
logger.add(
    Path(__file__).parent.parent.joinpath("logs").joinpath("ocr-proxy.log"),
    encoding='utf-8',
    rotation="00:00",
    retention=2,
    format=format_,
    backtrace=True,
    diagnose=True
)


# 生命周期
@asynccontextmanager
async def lifespan(app_):
    logger.info(f"Application name '{app_.title}'")
    logger.info(f"Application version '{app_.version}'")
    logger.info("Application server running")
    yield
    logger.info("Application server shutdown")


app = FastAPIOffline(
    title="ocr-proxy",
    version="0.1.0",
    debug=True,
    lifespan=lifespan,
)

app.include_router(api_router, prefix="/ocr")


@app.get("/health")
async def health_check():
    logger.info("Health check")
    return {"code": 200, "message": "ok", "data": None}
